package com.excesys.exsecs.scada.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.excesys.exsecs.admin.api.entity.SysFile;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.common.file.core.FileProperties;
import com.excesys.exsecs.common.file.core.FileTemplate;
import com.excesys.exsecs.common.file.local.LocalFileTemplate;
import com.excesys.exsecs.common.file.oss.OssProperties;
import com.excesys.exsecs.scada.entity.ScadaEntity;
import com.excesys.exsecs.scada.mapper.SysFileMapper2;
import com.excesys.exsecs.scada.service.ScadaFileService;
import com.excesys.exsecs.scada.util.JsonProcess;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.zip.ZipInputStream;

@Slf4j
@Service
@RequiredArgsConstructor
public class ScadaFileServiceImpl implements ScadaFileService {

	//private final OssProperties fileProperties;

	private final FileProperties fileProperties;
	private final FileTemplate fileTemplate;
	private final SysFileMapper2 sysFileMapper;
	private final FileProperties properties;
	private final JsonProcess jsonProcess;
	private final ScadaEntity scadaEntity;



	@Override
	public R localUpload(MultipartFile file) {
		List<String> zips = Arrays.asList("zip","rar","tar","gz");
		List<String> imgs = Arrays.
				asList("bmp","jpg","png","gif","fpx","svg","psd","raw","webp","apng");
		//生成文件名
		String fileName = IdUtil.simpleUUID()+ StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
		String suffix = FileUtil.extName(file.getOriginalFilename());
		Map<String,String> resultMap = new HashMap<>();
		resultMap.put("bucketName",fileProperties.getBucketName());
		//判断返回格式
		String type = "";
		if(zips.contains(suffix)){
			resultMap.put("fileName",fileName);
		}else if(imgs.contains(suffix)){
			resultMap.put("fileName",fileName);
			type="10";
		}
		//获取文件url
		resultMap.put("url",String.format("/admin/sys-file/local/scadafile/%s", fileName));
		try(InputStream inputStream = file.getInputStream()) {
			if(imgs.contains(suffix)){
				//上传图片oss
				fileTemplate.putObject(fileProperties.getBucketName(),fileName,inputStream,file.getContentType());
				resultMap.put("url",String.format("/admin/sys-file/oss/file?fileName=%s", fileName));
			}else {
				//fileTemplate.putObject(fileProperties.getBucketName(),fileName,inputStream,file.getContentType());
				//本地上传
				// 当 Bucket 不存在时创建
				String dir = scadaEntity.getBasePath() + FileUtil.FILE_SEPARATOR + fileProperties.getBucketName();
				if (!FileUtil.isDirectory(scadaEntity.getBasePath() + FileUtil.FILE_SEPARATOR + fileProperties.getBucketName())) {
					createBucket(fileProperties.getBucketName());
				}
				File localfile = new File(dir + FileUtil.FILE_SEPARATOR + fileName);
				FileUtil.writeFromStream(inputStream,localfile);
			}
			fileLog(file,fileName,type);
		} catch (Exception e) {
			log.error("----文件上传失败----"+LocalDateTime.now());
			e.printStackTrace();
		}
		//如果是压缩包，解压到指定目录
		if(zips.contains(suffix)){
			resultMap.put("url",String.format("/admin/sys-file/local/scadafile/%s", fileName));
			//获取文件相对路径
			String dir = scadaEntity.getBasePath()+ FileUtil.FILE_SEPARATOR +fileProperties.getBucketName()+FileUtil.FILE_SEPARATOR+fileName;
//			try {
//				File outFile = new File("D:\\usr\\exsecs\\Downloads\\zhongli");
//				ZipUtil.unzip(file.getInputStream(),outFile, Charset.defaultCharset());
//			} catch (IOException e) {
//				log.error("----解压失败----"+fileName);
//				throw new RuntimeException(e);
//			}
			unzip(dir);
			//替换image
		}
		return R.ok(resultMap,"上传成功");
	}

	private void fileLog(MultipartFile file,String fileName,String type){
		//创建SysFile对象并设置相关属性
		SysFile sysFile = new SysFile();
		sysFile.setFileName(fileName);
		// 对原始文件名进行编码转换
		String originalFilename = new String(
				Objects.requireNonNull(file.getOriginalFilename()).getBytes(StandardCharsets.ISO_8859_1),
				StandardCharsets.UTF_8);

		sysFile.setOriginal(originalFilename);
		sysFile.setFileSize(file.getSize());
		sysFile.setBucketName(fileProperties.getBucketName());
		sysFile.setType(type);
		// 调用save方法保存SysFile对象
		sysFileMapper.insert(sysFile);

	}
	/**
	 * 解压包到指定目录
	 * @param
	 */
	private void unzip(String path){
		File file = new File(path);
		String fileName = file.getName();
		String[] split = fileName.split("\\.");
		String absolutePath = file.getAbsolutePath();
		String outPutDir = absolutePath.substring(0,absolutePath.indexOf(fileProperties.getBucketName()));
		//解压文件到：D:\Users\excesysiot\Downloads\package\...
		try{
			ZipUtil.unzip(absolutePath, outPutDir+ "package\\" + split[0]);
		}catch (Exception e){
			log.error("An error occurred",e);
		}

		//判断是否是l5l vue2或vue3组件包
		File[] ls = FileUtil.ls(outPutDir+ "package\\" + split[0]);
		List<String> vueDir = new ArrayList<String>(Arrays.asList("meta2d-vue2","meta2d-vue3"));
		if(ls.length > 0 && ls[0].getName().contains("meta2d-vue")){
			String dirname = ls[0].getName();
			int i = dirname.lastIndexOf("meta2d-vue");
			String subdirname = dirname.substring(i);
			//替换image
			String filePath = outPutDir + "package" +FileUtil.FILE_SEPARATOR+ split[0] + FileUtil.FILE_SEPARATOR + subdirname + FileUtil.FILE_SEPARATOR + "public";
			jsonProcess.ChangeJson(filePath,split[0]);
		}
	}

	public void createBucket(String bucketName) {
		FileUtil.mkdir(scadaEntity.getBasePath() + FileUtil.FILE_SEPARATOR + bucketName);
	}
}
